<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="queryUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
          <el-button
            type="primary"
            icon="el-icon-circle-plus"
            @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column label="序号" type="index" width="50" align="center">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" align="center">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" align="center">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" align="center">
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="upUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button type="danger" icon="el-icon-delete" @click="del(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="success" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        width="30%"
        :visible.sync="dialogVisible"
        @close="closed"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密 码" prop="password">
            <el-input v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮 箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手 机" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        width="30%"
        :visible.sync="upUserVisible"
        @close="upClosed"
      >
        <el-form
          :model="upUserData"
          :rules="upUserRules"
          ref="upUserRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="upUserData.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮 箱" prop="email">
            <el-input v-model="upUserData.email"></el-input>
          </el-form-item>
          <el-form-item label="手 机" prop="mobile">
            <el-input v-model="upUserData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="upUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="upUserFn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    // 自定义校验规则
    var checkEamil = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+/
      if (regEmail.test(value)) {
        // 验证通过
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    var checkPhone = (rule, value, cb) => {
      // 验证手机的正则表达式
      const regEmail = /^1[0-9]{10}$/
      if (regEmail.test(value)) {
        // 验证通过
        return cb()
      }
      cb(new Error('请输入合法手机'))
    }
    return {
      // 添加用户对话框显示隐藏
      dialogVisible: false,
      // 修改用户对话框显示隐藏
      upUserVisible: false,
      // 查询参数
      queryInfo: {
        query: null,
        pagenum: 1,
        pagesize: 2,
      },
      // 用户列表
      userList: null,
      // 总条数
      total: null,
      // 添加用户表单
      ruleForm: {
        username: null,
        password: null,
        email: null,
        mobile: null,
      },
      // 修改用户表单
      upUserData: {
        username: null,
        email: null,
        mobile: null
      },
      // 表单验证规则 添加用户
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEamil, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机 ', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      // 修改用户
      upUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEamil, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机 ', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 删除
    del(val){
      this.$confirm ('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: true,
          type: 'warning'
        }).then(async () => {
          let {data: res} = await this.$http.delete(`users/${val}`)
          console.log("data",res);
          if(res.meta.status !== 200){
            return this.$message.error(res.meta.msg)
          }
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 修改
    async upUser(val) {
      this.upUserVisible = true
      let { data: res} = await this.$http.get(`users/${val.id}`)
      if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
      }
      this.upUserData = res.data
      console.log(res);
    },
    // 提交修改信息
    upUserFn(){
      this.$refs.upUserRef.validate(async (vaild) => {
        if (!vaild) return
        // 发起添加用户请求
        let { data: res } = await this.$http.put(`users/${this.upUserData.id}`, this.upUserData)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('修改成功!')
        this.upUserVisible = false
        this.getUserList()
      })
    },
    // 添加用户对话框 关闭触发事件
    closed() {
      this.$refs.ruleFormRef.resetFields()
    },
    upClosed(){
      this.$refs.upUserRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.ruleFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 发起添加用户请求
        let { data: res } = await this.$http.post('users', this.ruleForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('添加成功!')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 监听switch数据的改变
    async userStateChanged(val) {
      let { data: res } = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      )
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('更新用户状态失败!')
      }
      this.$message.success('更新用户状态成功!')
    },
    // 监听pagesize改变事件
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 监听页码值改变事件
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 获取用户列表
    async getUserList() {
      let { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败！')
      // 用户列表赋值
      this.userList = res.data.users
      // 总条数赋值
      this.total = res.data.total
    },
    // 查询用户
    async queryUser() {
      let { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) return this.$message.error('查询失败!')
      this.getUserList()
    },
  },
}
</script>
<style lang="less" scoped>
</style>